package assg.funnycells.server;

import gnu.getopt.Getopt;

import assg.funnycells.util.*;

public class Coordinator {
    static Configuration config;
    Server server;
    ActivityDisplay display;
    Logger logger;
    long termination;
    boolean displayOn;
    String title, infectedTeamName, antibodyTeamName;

    public Coordinator(long termination, boolean displayOn, String title, String infectedTeamName, String antibodyTeamName) {
	logger = Logger.getDefaultLogger();
	this.termination = termination;
	this.displayOn = displayOn;
	this.title = title;
	this.infectedTeamName = infectedTeamName;
	this.antibodyTeamName = antibodyTeamName;
    }

    public void start() {
	try {
	    display = new ActivityDisplay(title, displayOn, termination, infectedTeamName, antibodyTeamName);
	    server = new Server(display);
	    display.setServerState(server.serverState());
	    server.serverState().terminationTimeout(termination);
	    server.start();
	} catch(Exception e) {
	    logger.error("Server error: Exiting...", e);
	}
    }

    public static Configuration getConfig() {
	return config;
    }

    public static void main(String[] args) {
	Getopt g = new Getopt("coordinator", args, "c:l:x:v:t:r:g:");
	int c;
	String configPath = "funnycells.conf";
	String title = "";
	long termination = 0;
	boolean displayOn = true;
	String infectedTeamName = "Infected";
	String antibodyTeamName = "Antibody";

	while((c = g.getopt()) != -1) {
	    switch(c) {
	    case 'c':
		configPath = g.getOptarg();
		break;
	    case 'l':
		int logLevel = StringOperations.parseInt(g.getOptarg());
		if(logLevel > -1)
		    Logger.getDefaultLogger().setLogLevel(logLevel);
		break;
	    case 'x':
		termination = StringOperations.parseLong(g.getOptarg());
		break;
	    case 'v':
		displayOn = (StringOperations.parseInt(g.getOptarg()) == 1 ? true : false);
		break;
	    case 't':
		title = g.getOptarg();
		break;
	    case 'r':
		infectedTeamName = g.getOptarg();
		break;
	    case 'g':
		antibodyTeamName = g.getOptarg();
		break;
	    }
	}
	config = new Configuration(configPath);

	(new Coordinator(termination, displayOn, title, infectedTeamName, antibodyTeamName)).start();
    }

}